import socket,_thread,time

# udp_recv = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
# # udp_recv.bind(('0.0.0.0',10240))
# msg=b'hello word'
# desNode=('192.169.0.240',10241)
# udp_recv.sendto(msg  ,desNode)

class UdpModel:
    LogInfo=lambda str:{print(str)}
    def __init__(self,recvePort=10240,recvCallBack=lambda msg:{print(msg)}) -> None:
        self.sendList = [] #数据发送队列(data,des_addr(ip,prot))
        self.recvCallBack = recvCallBack #数据接收到的回调
        self.recvPort = recvePort #接收端口
        self.udpSend = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        self.udpRecv = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        self.sendLock =_thread.allocate_lock()
        try:
            self.udpRecv.bind(('0.0.0.0',self.recvPort))#绑定端口
        except:
            UdpModel.LogInfo(f"bind recvePort erro{recvePort}")
            self.udpRecv.close()
        pass
    def send(self,data):
        print(data)
        self.sendLock.acquire()
        self.sendList.append(data)
        print(self.sendList)
        self.sendLock.release()
        pass
    
    def run(self):
        #开启发送线程
        _thread.start_new_thread(self.sendThread,())
        #开启接收线程
        _thread.start_new_thread(self.recvThread,())
        pass

    def sendThread(self):
        print('sendThread')
        while True:
            if len(self.sendList) != 0:
                self.sendLock.acquire()
                sendInfo = self.sendList.copy()
                print(sendInfo,"data send1")
                self.sendList.clear()
                self.sendLock.release()
                print(sendInfo,"data send2")
                for msg in sendInfo:
                    print(msg,"send to")
                    try:
                        self.udpSend.sendto(msg[0],msg[1])
                    except:
                        print("send erro ")
                    pass
                pass
            time.sleep(1)
            #print('sendThread check')
            pass
        pass

    def recvThread(self):
        print('recvThread')
        # 循环接收数据  
        while True:  
            data, addr = self.udpRecv.recvfrom(1024)  
            self.recvCallBack((data,addr))
            UdpModel.LogInfo(f"recvData{data}")
            time.sleep(1)
        pass

print (__name__)

if __name__ == '__main__' :
    Udp=UdpModel()
    Udp.run()
    while True:
        Udp.send((b'hellow ',('192.168.31.193',12345)))
        time.sleep(5)
    pass